import { createRouter, createWebHistory } from 'vue-router';
import { useUserStore } from '@/stores/user';
import { staticRoutes, layoutRoute } from './routes';
import http from '@/utils/request';
import { usePermissionStore } from '@/stores/permission';

const router = createRouter({
  history: createWebHistory(),
  routes: [...staticRoutes, layoutRoute],
  scrollBehavior: () => ({ top: 0 })
});

const whiteList = ['/login', '/404', '/front']; // 白名单定义

router.beforeEach(async (to, from, next) => {
  console.log('[导航开始] 当前路径:', to.path, '来源路径:', from.path);

  if (to.meta.title) {
    document.title = `${to.meta.title} - 小花在线图书馆`;
  } else {
    document.title = '小花在线图书馆';
  }

  const userStore = useUserStore();
  const permissionStore = usePermissionStore();
  console.log('[用户状态] token存在:', !!userStore.library_token, '角色:', userStore.roles);

  // 1. 白名单检查
  if (whiteList.some(path => to.path.startsWith(path))) {
    console.log('[白名单] 直接放行');
    next();
    return;
  }

  // 2. 权限路由标识
  const isAuthRoute = to.path.startsWith('/dashboard/');

  // 3. 未登录访问受保护路由
  if (!userStore.library_token && isAuthRoute) {
    console.warn('[权限拦截] 未登录访问受保护路由');
    next(`/login?redirect=${encodeURIComponent(to.fullPath)}`);
    return;
  }

  // 4. 已登录处理逻辑
  if (userStore.library_token) {
    console.log('[已登录] 开始处理逻辑');
    
    // 4.1 获取用户信息
    if (!userStore.library_users.roles.length) {
      console.log('[用户信息] 开始获取角色信息');
      try {
        const infoRes = await http.get('/user/getInfo');
        userStore.roles = infoRes.data.roles;
      } catch (error) {
        userStore.logout();
        next('/login');
        return;
      }
    }

    // 4.2 动态路由处理
    if (userStore.roles.length && !permissionStore.hasGenerated) {
      console.log('[路由生成] 开始生成动态路由');
      
      await permissionStore.generateRoutes(userStore.roles);

      // 清除旧路由（防止重复添加）
      permissionStore.routes.forEach(route => {
        if (router.hasRoute(route.name)) {
          router.removeRoute(route.name);
        }
      });

      // 将生成的路由添加到layoutRoute的子路由
      permissionStore.routes.forEach(route => {
        router.addRoute('layoutRoute', {
          ...route,
          path: route.path.startsWith('/') ? route.path.slice(1) : route.path
        });
      });

      console.log('[路由生成] 新增路由数量:', permissionStore.routes.length);
      permissionStore.setHasGenerated(true);
      console.log('[路由生成] 完成，跳转目标:', to.redirectedFrom?.path || '/dashboard/overview');

      next({ 
        path: to.redirectedFrom?.path || '/dashboard/overview',
        replace: true,
        query: to.query,
        hash: to.hash
      });
      return;
    }

    // 4.3 已登录访问登录页
    if (to.path === '/login') {
      console.log('[导航拦截] 已登录访问登录页，重定向到控制台');
      next('/dashboard/overview');
      return;
    }
  }

  console.log('[导航放行] 进入最终next()');
  next();
});

export { router };
export default router;